canvas如何自适应窗口大小 您所在的位置:网站首页 canvas 尺寸 canvas如何自适应窗口大小

canvas如何自适应窗口大小

#canvas如何自适应窗口大小| 来源: 网络整理| 查看: 265

问题

canvas的宽高不能用百分比来显示,如果想用canvas做一个图希望能够自适应窗口宽度怎么办。

正文

这里我们先画了一个宽为canvas宽度的红色矩形,这样canvas如何变化自己的宽度,矩形都可以跟着改变。

doctype html> 页面名称 /** @type {HTMLCanvasElement} */ const canvas = document.getElementById('box') const ctx = canvas.getContext('2d') const draw = () => { const { width } = canvas ctx.fillStyle = 'red' //用canvas的宽长绘图 ctx.fillRect(0, 0, width, 50) } draw()

在这里插入图片描述

我们希望这个红色的矩形作为网页顶部的导航。

那么它必须宽达到网页的百分百,那么我们可以把父级div的百分百宽度赋予给他。

doctype html> 页面名称 /** @type {HTMLCanvasElement} */ const canvas = document.getElementById('box') const ctx = canvas.getContext('2d') const draw = () => { //获取父级宽度并赋值给canvas const contentWidth = document.getElementById('content').clientWidth canvas.width = contentWidth const { width } = canvas ctx.fillStyle = 'red' ctx.fillRect(0, 0, width, 50) } draw()

在这里插入图片描述 看似达到了效果,但是当我们缩小页面时,发现了问题。 在这里插入图片描述 因为我们赋予canvas宽度时传入的是定值,而网页缩小时,canvas的宽度还是没有改变。

于是我们可以想到监听网页的缩放事件。

每次缩放都重新将重新改变canvas的宽度重新绘制。

doctype html> 页面名称 /** @type {HTMLCanvasElement} */ const canvas = document.getElementById('box') const ctx = canvas.getContext('2d') const draw = () => { const contentWidth = document.getElementById('content').clientWidth canvas.width = contentWidth const { width } = canvas ctx.fillStyle = 'red' ctx.fillRect(0, 0, width, 50) } draw() //窗口缩放事件 window.onresize = function () { draw() }

问题解决。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有